<template>
	<div class="wrap-content">
		<el-form :inline="true" label="名称" :model="searchData" class="search-form">
			<el-form-item>
				<el-input v-model="searchData.title" placeholder="请输入名称"></el-input>
			</el-form-item>
			<el-form-item>
				<el-input v-model="searchData.introduce" placeholder="请输入详情"></el-input>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="onSearchGoods">查询</el-button>
			</el-form-item>
		</el-form>

		<el-table :data="dataList" border style="width: 100%">
			<el-table-column prop="id" label="序号" width="180"></el-table-column>
			<el-table-column prop="title" label="名称" width="180"></el-table-column>
			<el-table-column prop="introduce" label="详情"></el-table-column>
		</el-table>

		<el-pagination
			class="pagination"
			background
			layout="sizes, prev, pager, next"
			:total="searchData.total"
			:page-size="searchData.pageSize"
			:page-sizes="[5, 10, 15, 20]"
			@current-change="onCurrentChange"
			@size-change="onSizeChange"
		/>
	</div>
</template>

<script lang="ts" setup>
import { getProjectList } from '@/api/project'

interface IProjectItem {
	id: number
	userId: number
	title: string
	introduce: string
}

const projectList = ref<IProjectItem[]>([])
const dataList = ref<IProjectItem[]>([])
const searchData = reactive({
	page: 1,
	pageSize: 5,
	total: 0,
	title: '',
	introduce: ''
})

const onCurrentChange = (page: number) => {
	searchData.page = page
}

const onSizeChange = (pageSize: number) => {
	searchData.pageSize = pageSize
}

const onSearchGoods = () => {
	let res: IProjectItem[] = []
	if (searchData.title || searchData.introduce) {
		if (searchData.title) {
			res = projectList.value.filter((project) => project.title.indexOf(searchData.title) > -1)
		}
		if (searchData.introduce) {
			res = (res.length > 0 ? res : projectList.value).filter(
				(project) => project.introduce.indexOf(searchData.introduce) > -1
			)
		}
	} else {
		res = projectList.value
	}
	searchData.page = 1
	searchData.total = res.length
	dataList.value = res
}

const fetchData = () => {
	getProjectList().then((resp) => {
		projectList.value = resp
		searchData.total = projectList.value.length
	})
}

watchEffect(() => {
	const start = (searchData.page - 1) * searchData.pageSize
	dataList.value = projectList.value.slice(start, start + searchData.pageSize)
})

onMounted(() => {
	fetchData()
})
</script>

<style lang="less" scoped>
.wrap-content {
	display: flex;
	height: max-content;
	flex-direction: column;

	.pagination {
		display: flex;
		margin: 10px;
	}
}
</style>
